package com.hibernate.daoimp.front;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MultiSearcher;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.common.Constant;
import com.common.Page;
import com.hibernate.dao.front.IndexDao;
import com.hibernate.pojo.Articles;
import com.hibernate.pojo.Product;
import com.hibernate.pojo.ProductAndProductAtrribute;

public class IndexDaoImp extends HibernateDaoSupport implements IndexDao{

	private List list;
	public int record_count=0;
	
	public List findCorrelation(String hql)
	{
		return this.getHibernateTemplate().find(hql);
	}
	
	/**
	 * display every one article
	 */
	public Map findArticle(Long id)
	{
		Articles article=(Articles)this.getHibernateTemplate().load(Articles.class, id);
		Map map=new HashMap();
		map.put("title", article.getTitle());
		map.put("author",article.getAuthor() );
		map.put("leibie",article.getLeibie() );
		map.put("create_time",article.getCreate_time() );
		map.put("content",article.getContent() );
		map.put("linkurl",article.getLinkurl() );
		map.put("intr",article.getIntr() );
		map.put("keyword",article.getKeyword() );
		map.put("ingUrl",article.getImgUrl() );
		return map;
	}
	
	/**
	 * display every categry articles list
	 */
	public Map findArticleList(int page,final int categryID,int jump)
	{
		Map hashmap=new HashMap();
		record_count=page*Constant.FRONT_ARTICLE_VIEW_COUNT;
		if(categryID==0)
		{
			list=this.getHibernateTemplate().find("select count(*) from Articles");
		}
		else
		{
			list=this.getHibernateTemplate().find("select count(*) from Articles where leibie="+categryID);
		}
		Integer counts=(Integer)list.get(0);
		Page pageobject=new Page();	
		Map map=pageobject.pageCount(counts,Constant.FRONT_ARTICLE_VIEW_COUNT);
		map.put("pagecur", page);
		map.put("articlesleibieID",categryID);
		
		//page config
		/**
		String str="";
		String init_page="";
		System.out.println(jump);
		if(jump==0)
		{
			int end=page/10;
			System.out.println(end);
			end=end*10;
			System.out.println(end);
			init_page=end+"";
			for(int i=0;i<10;i++)
			{
				if(i==9)
					str+=end;
				else
					str+=end+",";
				System.out.println(str);
				end++;
			}
		}
		else
		{
			int end=jump+10;
			init_page=end+"";
			for(int i=0;i<10;i++)
			{
				if(i==9)
					str+=end;
				else
				{
					str+=end+",";
				}
				end++;
			}
		}
		map.put("numbers", str);
		map.put("init_page", init_page);
		 */
		hashmap.put("page_content", map);
		list=getHibernateTemplate().executeFind(new HibernateCallback(){
		public Object doInHibernate(Session session)throws HibernateException, SQLException
		{
			String hql_news;
			Query query;
			if(categryID==0)
			{
				hql_news=" from Articles order by ID desc";
				query = session.createQuery(hql_news);
				query.setFirstResult(record_count);
				query.setMaxResults(Constant.FRONT_ARTICLE_VIEW_COUNT);
			}
			else
			{
				hql_news=" from Articles where leibie=? order by ID desc";
				query = session.createQuery(hql_news);
				query.setInteger(0, categryID);
				query.setFirstResult(record_count);
				query.setMaxResults(Constant.FRONT_ARTICLE_VIEW_COUNT);
			}
				List list = query.list();
				return list;
		}
		});
		hashmap.put("news_list", list);
		return hashmap;
	}
	
	/**
	 * product list
	 */
	public Map findProductList(int page, final int categryID,int jump)
	{
		Map hashmap=new HashMap();
		record_count=page*Constant.FRONT_PRODUCT_VIEW_COUNT;
		if(categryID==0)
		{
			list=this.getHibernateTemplate().find("select count(*) from Product");
		}
		else
		{
			list=this.getHibernateTemplate().find("select count(*) from Product where categry_id="+categryID);
		}
		Integer counts=(Integer)list.get(0);
		Page pageobject=new Page();	
		Map map=pageobject.pageCount(counts,Constant.FRONT_PRODUCT_VIEW_COUNT);
		map.put("pagecur", page);
		map.put("productleibieID",categryID);
		
		hashmap.put("page_content", map);
		list=getHibernateTemplate().executeFind(new HibernateCallback(){
		public Object doInHibernate(Session session)throws HibernateException, SQLException
		{
			String hql_news;
			Query query;
			if(categryID==0)
			{
				hql_news=" from Product order by ID desc";
				query = session.createQuery(hql_news);
				query.setFirstResult(record_count);
				query.setMaxResults(Constant.FRONT_PRODUCT_VIEW_COUNT);
			}
			else
			{
				hql_news=" from Product where categry_id=? order by ID desc";
				query = session.createQuery(hql_news);
				query.setInteger(0, categryID);
				query.setFirstResult(record_count);
				query.setMaxResults(Constant.FRONT_PRODUCT_VIEW_COUNT);
			}
				List list = query.list();
				return list;
		}
		});
		hashmap.put("product_list", list);
		return hashmap;
	}
	
	/**
	 * lucene search
	 */
	public Map findSearchResult(String serchString,int page)
	{
		List list=new ArrayList();
		Map map=null;
		Map hashmap=new HashMap();
		try
		{
		/* 创建一个搜索，搜索刚才创建的d:\\save\\目录下的索引 */
		  IndexSearcher indexSearcher = new IndexSearcher(Constant.INDEX_PATH);
		  /* 在这里我们只需要搜索一个目录 */
		  IndexSearcher indexSearchers[] = { indexSearcher };
		  /* 我们需要搜索两个域"ArticleTitle", "ArticleText"里面的内容 */
		  String[] fields = { "ProductTitle", "ProductKeyword" };
		  /* 下面这个表示要同时搜索这两个域，而且只要一个域里面有满足我们搜索的内容就行 */
		  BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD,
		    BooleanClause.Occur.SHOULD};
		  /*
		   * MultiFieldQueryParser表示多个域解析，
		   * 同时可以解析含空格的字符串，如果我们搜索"中国 金牌"，根据前面的索引，显然搜到的是第二份文件
		   */
		  org.apache.lucene.search.Query query = MultiFieldQueryParser.parse(serchString, fields, clauses,
		    new StandardAnalyzer());
		  /* Multisearcher表示多目录搜索，在这里我们只有一个目录 */
		  MultiSearcher searcher = new MultiSearcher(indexSearchers);
		  /* 开始搜索 */
		  Hits h = searcher.search(query);
		  //分页
		  record_count=page*Constant.FRONT_SEARCH_VIEW_COUNT;
		  Page pageobject=new Page();	
		  Map map1=pageobject.pageCount(h.length(),Constant.FRONT_SEARCH_VIEW_COUNT);
		  map1.put("pagecur", page);
		  map1.put("search_keyword",serchString);		
		  hashmap.put("page_content", map1);
		  int end;
		  if(record_count+Constant.FRONT_SEARCH_VIEW_COUNT>=h.length())
			  end=h.length()-1;
		  else
			  end=record_count+Constant.FRONT_SEARCH_VIEW_COUNT;
		  //封装成list
		  String str="";
		  for (int i = record_count; i <= end; i++) {
			  map=new HashMap();
			  Document doc=h.doc(i);
			  map.put("id", doc.get("ProductId"));
			  str=doc.get("ProductTitle").replace(serchString, "<font color=#FF0000>"+serchString+"</font>");
			  map.put("title", str);
			  str=doc.get("ProductDepict").replace(serchString, "<font color=#FF0000>"+serchString+"</font>");
			  map.put("keyword", str);
			  list.add(map);
		  }
		  searcher.close();
		  
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		hashmap.put("result",list );
		return hashmap;
	}
	
	
	/**
	 * display every one product
	 */
	public Map findProduct(Long id)
	{
		Product product=(Product)this.getHibernateTemplate().load(Product.class, id);
		Map map=new HashMap();
		map.put("id", product.getId());
		map.put("product_name", product.getProduct_name());
		map.put("product_depict", product.getProduct_depict());
		map.put("product_pic", product.getProduct_pic());
		map.put("product_content",product.getProduct_content());
		map.put("product_price", product.getProduct_price());
		map.put("product_count", product.getProduct_count());
		map.put("product_author", product.getCategry_id());
		map.put("keyword",product.getKeyword());
		List list=this.getHibernateTemplate().find("from ProductAndProductAtrribute where product_id="+map.get("id"));
		if(list.size()>0)
		{
			ProductAndProductAtrribute papa;
			for(int i=0;i<list.size();i++)
			{
				papa=(ProductAndProductAtrribute)list.get(i);
				map.put("atrribute_id"+papa.getAtrribute_id(),papa.getAtrribute_value() );
			}
		}
		return map;
	}
}
